﻿using Entity;
using IHotelDAL;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HotelDAL
{
    public class BaseDAL<T> : IBaseDAL<T> where T:BaseEntity
    {
        HotelDbContext _dbContext;

        public BaseDAL(HotelDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        public HotelDbContext GetContext()
        {
            return _dbContext;
        }
        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool CreateEntity(T entity)
        {
            _dbContext.Set<T>().Add(entity);
            return _dbContext.SaveChanges() > 0;
        }

        /// <summary>
        /// 真删除实体
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool DeleteEntity(T entity)
        {
            if (entity == null)
            {
                return false;
            }
            else
            {
                _dbContext.Set<T>().Remove(entity);
                return _dbContext.SaveChanges() > 0;
            }
        }

        /// <summary>
        /// 真删除实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteEntity(string id)
        {
            var entity = _dbContext.Set<T>().FirstOrDefault(d => d.Id == id);
            if (entity == null)
            {
                return false;
            }
            else
            {
                _dbContext.Set<T>().Remove(entity);
                return _dbContext.SaveChanges() > 0;
            }
        }

        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool UpdateEntity(T entity)
        {
            if (entity == null)
            {
                return false;
            }
            else
            {
                _dbContext.Set<T>().Update(entity);
                return _dbContext.SaveChanges() > 0;
            }
        }

        /// <summary>
        /// 获取实体数据集
        /// </summary>
        /// <returns></returns>
        public DbSet<T> GetEntities()
        {
            return _dbContext.Set<T>();
        }

    }
}
